package com.lanhu.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.lanhu.demo.entity.User;
import com.lanhu.demo.service.UserService;
import com.lanhu.demo.utils.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/add", method = RequestMethod.POST)
    public Object addUser(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String username = request.getParameter("username").trim();
        String email = request.getParameter("email").trim();
        String password = request.getParameter("password").trim();

        if (email == null || email.equals("")) {
            jsonObject.put(Const.CODE, 0);
            jsonObject.put(Const.MSG, "注册邮箱不能为空");
            return jsonObject;
        }
        if (password == null || password.equals("")) {
            jsonObject.put(Const.CODE, 0);
            jsonObject.put(Const.MSG, "密码不能为空");
            return jsonObject;
        }

        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(password);
        boolean flag = userService.insert(user);
        if (flag) {
            jsonObject.put(Const.CODE, 1);
            jsonObject.put(Const.MSG, "添加成功");
            return jsonObject;
        }
        jsonObject.put(Const.CODE, 0);
        jsonObject.put(Const.MSG, "添加失败");
        return jsonObject;
    }

    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public Object loginStatus(HttpServletRequest request, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        String email = request.getParameter("email").trim();
        String password = request.getParameter("password").trim();
        boolean flag = userService.verifyPassword(email, password);
        if (flag) {
            jsonObject.put(Const.CODE, 1);
            jsonObject.put(Const.MSG, "登录成功");
            return jsonObject;
        }
        jsonObject.put(Const.CODE, 0);
        jsonObject.put(Const.MSG, "登录失败");
        return jsonObject;
    }
}
